//
//  UserAccount.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/12.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit
import Alamofire

class UserAccount: NSObject , Printable , NSCoding{
    
    /**
    access_token	用于调用access_token，接口获取授权后的access token
    expires_in      access_token的生命周期，单位是秒数
    remind_in       access_token的生命周期（该参数即将废弃，开发者请使用expires_in）
    uid             当前授权用户的UID
    */
    
    let access_token : String
    let expires_in : NSTimeInterval
    let expiresDate : NSDate
    let uid : String
    // 用户昵称
    var name : String?
    // 用户头像地址,大图
    var avatar_large : String?
    
    // 字典转模型
    init(dict: [String: AnyObject]) {
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        uid = dict["uid"] as! String
        name = dict["name"] as? String
        avatar_large = dict["avatar_large"] as? String
    }
    
    static let accountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String).stringByAppendingPathComponent("account.plist")
    
    /**
    class func loadAccessToken(params: [String: String], completion:(account: UserAccount?, error: NSError?)->()) {
    let urlString = "https://api.weibo.com/oauth2/access_token"
    
    Alamofire.request(.POST, urlString, parameters: params).responseJSON() { (_, _, JSON, error) in
    
    // 如果出现错误，直接回调并且返回
    if error != nil || JSON == nil {
    completion(account: nil, error: error)
    return
    }
    
    // JSON 有可能是字典也有可能是数组
    // 字典转模型
    let account = UserAccount(dict: JSON as! [String : AnyObject])
    
    // 加载用户信息 － uid 包含在 account 中
    account.loadUserInfo(completion)
    }.responseString() { (_, _, JSONString, _) in
    println(JSONString)
    }
    }

    **/
    
    class func loadAccessToken (params:[String:AnyObject],completion:(account : UserAccount?) -> ()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        NetWorkTools.requestJSON(.POST, URLString: urlString, parameters: params) { (json) -> () in
            if json == nil {
                completion(account: nil)
                return
            }
            
            let account = UserAccount(dict: json as! [String:AnyObject])
            account.loadUserInfo(completion)
        }
    }
    
    // 设置用户全局属性
    // 从本地读取用户信息
    class func loadUserAccount() -> UserAccount?{
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount {
            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return account
            }
        }
        return nil
    }
    
    // 加载用户信息
    func loadUserInfo(completion:(account : UserAccount?) -> ()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["access_token": access_token,"uid":uid]
        
        NetWorkTools.requestJSON(.GET, URLString: urlString, parameters: params) { (json) -> () in
            // 给对象设置属性
            if let dict = json as? [String : AnyObject]{
                self.name = dict["name"] as? String
                self.avatar_large = dict["avatar_large"] as? String
                // 归档
                NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
                // 回调函数
                completion(account : self)
            }else{
                // json 解析错误
                let jsonError = NSError(domain: "WeiBo", code: -1, userInfo: ["error":"数据解析错误"])
                completion(account : nil)
            }
        }
    }
    
    
    override var description : String {
        let properties = ["access_token","expires_in","expiresDate","uid","name","avatar_large"];
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
    // MARK: - 编码器解码器
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate,forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name,forKey:"name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
     required init(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as! NSTimeInterval
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate
        uid = aDecoder.decodeObjectForKey("uid") as! String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
   
}
